<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref } from 'vue'
import { CurdData } from '@/api/logisticsCompany/types'
import useSchema from './hooks/useSchema'
import { SchemaConfig } from '@/api/global/types'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
import { FieldEnum } from '@/api/logisticsCompany/types'
import { getFieldEnumApi } from '@/api/logisticsCompany'

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

// Begin CRUD Template Block
// ------------------------
const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const fieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    fieldEnum.value = res.data

    const schemaConfig: SchemaConfig = {
      actionButtonsTemplate: undefined,
      fieldEnum: fieldEnum.value
    }
    console.log('fieldEnum', fieldEnum.value)

    // 获取表单配置
    const { crudSchemas } = useSchema(schemaConfig)
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      formSchema: newSchemas.formSchema || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })
// End CRUD Template Block
// ------------------------

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form @register="formRegister" :schema="allSchemas.formSchema" />
</template>
